// plugins/toast.js
import { createApp, h } from 'vue'
import ToastMessage from './vToast.vue';

export const vToast = (options) => {
    return new Promise((resolve) => {
        const container = document.createElement('div')
        document.body.appendChild(container)

        const tempApp = createApp({
            render() {
                return h(ToastMessage, {
                    ...(typeof options === 'string' ? { 
                      title: '提示',
                      message: options,
                      type: 'info'
                    } : {
                      title: options.title || '提示',
                      message: options.message,
                      icon: options.icon,
                      duration: options.duration,
                      position: options.position,
                      type: options.type || 'info'
                    }),
                    onClosed: () => {
                        tempApp.unmount()
                        container.remove()
                        resolve()
                    }
                })
            }
        })

        tempApp.mount(container)
    })
}

// 快捷方法
vToast.success = (message, duration = 2000) => {
  return vToast({
    title: '成功',
    message,
    icon: 'icon-success',
    duration,
    type: 'success'
  })
}

vToast.error = (message, duration = 2000) => {
  return vToast({
    title: '错误',
    message,
    icon: 'icon-error',
    duration,
    type: 'error'
  })
}

vToast.warning = (message, duration = 2000) => {
  return vToast({
    title: '警告',
    message,
    icon: 'icon-alert',
    duration,
    type: 'warning'
  })
}
vToast.warn = (message, duration = 22000) => {
  return vToast({
    title: '警告',
    message,
    icon: 'icon-alert',
    duration,
    type: 'warning'
  })
}

vToast.info = (message, duration = 2000) => {
  return vToast({
    title: '提示',
    message,
    icon: 'icon-help',
    duration,
    type: 'help'
  })
}

export default {
    install(app) {
        app.config.globalProperties.$vToast = vToast
        app.component('ToastMessage', ToastMessage);
    }
}